package com.gz.steak.utils.jwt;

/**
 * @Author 刘牌
 * @Date 2020/2/22 0022 12:53
 * @Version 1.0
 */

import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.common.exception.EmBusinessError;
import com.gz.steak.modules.system.pojo.dataobject.SysUser;
import com.gz.steak.modules.system.pojo.model.LoginModel;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JWTUtil {

    //创建jwt
    public static String createJWT(long expirationDate, LoginModel user) {
        //签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //生成Jwt时间
        long jwtTime = System.currentTimeMillis();
        Date date = new Date(jwtTime);
        //创建payload私有声明
        Map<String, Object> map = new HashMap<>();
        map.put("username", user.getUserName());
        map.put("password", user.getUserPassword());
        map.put("roles", user.getRoles());
        map.put("roleIdList",user.getRoleIdList());
        //生成签名的时候使用的密钥secret
        String key = user.getUserPassword();

        //签发人
        String subject = user.getUserName();
        //为payload添加各种标准
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(map)
                .setId(UUID.randomUUID().toString().replace("_", ""))
                .setIssuedAt(date)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (expirationDate >= 0) {
            //过期时间为当前时间加上10分钟
            long expDate = jwtTime + expirationDate;
            Date exp = new Date(expDate);
            jwtBuilder.setExpiration(exp);
        }
        return jwtBuilder.compact();
    }

    //Token解密
    public static Claims decryptJWT(String token, SysUser user) {
        //签名密钥
        String key = user.getUserPassword();

        Claims claims = Jwts.parser().setSigningKey(key)
                //需要解析的jwt
                .parseClaimsJws(token).getBody();
        return claims;
    }

    //验证token
    public static Boolean checkJWT(String token, LoginModel user){
        //签名密钥
        String key = user.getUserPassword();
        try {
            Claims claims = Jwts.parser().setSigningKey(key)
                    .parseClaimsJws(token).getBody();
            if(claims.get("password").equals(user.getUserPassword())){
                return true;
            }
        }catch (RuntimeException e){
            throw new BusinessException(EmBusinessError.IDENTITY_EXPIRED);
        }
        return false;
    }

}

